import $axios from 'axios'
import router from '@/router' //引入路由
import {
	Message,
	MessageBox,
	Loading
} from 'element-ui'
import {
	setAuthorization, //设置认证信息
	delAuthorization //清除登录信息
} from "@/api/layout/layout.js"
/* axios 为自定义实例，不是通用axios对象 */
window.baseURL = '/api/ccms/'//公用路径
const axios = $axios.create({
	baseURL: baseURL //设置公用转发路径
});
// $axios.defaults.headers.common['access_token'] = "d54e3ef7-6d69-4b4e-afb3-ef539cb80f9b"; //设置公用token
/* 请求拦截，智能设置请求体，自动设置报文类型为json */
let loadingInstance; //全局加载动画
let errorMsg; //全局错误提示
let requestLen = 0; //记录请求次数
axios.interceptors.request.use(function(config) {
	//每次请求之前，把存储在cookie中的认证信息设置到请求头中
	setAuthorization().then(Authorization => {
		config.headers.common['Authorization'] = Authorization; //把认证信息设置到请求头
	})
	requestLen += 1; //每发出一次请求，请求次数+1
	loadingInstance = Loading.service({
		background: "transparent"
	});
	if (!config.data) {
		config.data = {};
	}
	if (config.headers['isMork']) {
		delete config.headers['isMork'];
		config.baseURL = "/static/mork";
		config.url += ".json";
		config.data = {};
		config.method = "get";
	}
	return config;
}, function(error) {
	return Promise.reject(error);
})
/* 响应拦截，登录跳转 */
axios.interceptors.response.use(
	response => {
		setAuthorization(response.headers.Authorization)//更新认证信息
		requestLen -= 1;
		if (requestLen < 1) loadingInstance.close();
		if (response.data.code && response.data.code !== 10000) {
			if (errorMsg) errorMsg.close();
			errorMsg = Message.warning(response.data.msg.replace(/参数校验异常: |程序执行异常，原因: /,""))//后端提示改造
		}
		return response
	},
	error => {
		requestLen -= 1;
		if (requestLen < 1) loadingInstance.close();
		if (errorMsg) errorMsg.close();
		if (error.response.status === 401) {
			setAuthorization().then(() => { //本地存有认证信息（失效），则提示用户是否退出
				//清除登录信息
				MessageBox.confirm('当前登录已失效, 是否重新登录?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => { //本地无认证信息，则直接回跳到登录页
					delAuthorization(true) //回到登录页
				})
			}).catch(() => {
				location.href = "/login" //回到登录页
			})

		} else {
			errorMsg = Message.error('服务正在重启或者已经挂了...')
		}
		return Promise.reject(error)
	}
)
export default axios
